package com.chap17.completablefuture;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * <code>Demo22</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-12 14:09
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class Demo22 {
    public static void main(String[] args) {
        //任务1
        CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
            log.debug("T1:洗水壶");
            sleep(1, TimeUnit.SECONDS);

            log.debug("T1:烧开水");
            sleep(15, TimeUnit.SECONDS);
        });

        //任务2
        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
            log.debug("T2:洗茶壶");
            sleep(1, TimeUnit.SECONDS);

            log.debug("T2:洗茶杯");
            sleep(2, TimeUnit.SECONDS);

            log.debug("T2:拿茶叶");
            sleep(1, TimeUnit.SECONDS);
            return "龙井";
        });

        // //任务3  __表示没有返回值
        CompletableFuture<String> f3 = f1.thenCombine(f2, (__,s) -> {
            log.debug("T1:拿到茶叶：{}", s);

            log.debug("T1:泡茶");
            return "上茶：" + s;
        });

        log.debug(f3.join());
    }

    private static void sleep(int i, TimeUnit seconds) {
        try {
            seconds.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
